// axios请求函数模块
import axios from 'axios'
import qs from 'qs'
import { Loading, Message } from 'element-ui'

//初始化
let loading;

//开始动画
function startLoading() {
    loading = Loading.service({
        lock: true,
        text: "正在努力的加载中..."
    })
}

//结束动画
function closeLoading() {
    loading.close();
}

// const token = localStorage.getItem('token');
let logger = process.env.LOGGER;
let environment = process.env.NODE_ENV;
//全局axios默认值
axios.defaults.baseURL = process.env.BASE_URL; //配置个地址以后只需传入地址后缀
axios.defaults.timeout = 0;//超时时间三分钟
//拦截器
// 请求拦截
axios.interceptors.request.use(config => {

    config.headers.Authorization = "Bearer " + localStorage.getItem("token")

    //判断当前请求是否设置了不显示Loading
    startLoading();
    return config;
}, error => {
    closeLoading();
    Message.error('请求超时!');
    return Promise.reject(error);
});

// 响应拦截
axios.interceptors.response.use(response => {
    closeLoading();
    let resp = response.data;
    if (logger) {
        // console.log(resp, environment);
    }
    switch (resp.code) {
        case 401:
            Message.error("没有访问权限");
            localStorage.removeItem('token'); //删除用户登录验证的key值，即token值
            router.replace({
                path: '/'
            });
            return;
        case 500:
            Message.error(resp.message);
            return Promise.reject();
    }
    return response;
}, error => {
    closeLoading();
    return Promise.reject(error);
});

//封装get请求和post请求
export default {
    post(url, data = {}) {
        return new Promise((resolve, reject) => {
            axios.post(url, data)
                .then(response => {
                    resolve(response.data)
                }, err => {
                    reject(err)
                })
        })
    },
    postForm(url, data = {}) {
        return new Promise((resolve, reject) => {
            axios.post(url, qs.stringify(data), {
                    headers: {
                        'Content-Type': "application/x-www-form-urlencoded"
                    }
                })
                .then(response => {
                    resolve(response.data)
                }, err => {
                    reject(err)
                })
        })
    },
    postFile(url, data = {}) {
        return new Promise((resolve, reject) => {
            axios.post(url, data, {
                    headers: {
                        'Content-Type': 'multipart/form-data'
                    }
                })
                .then(response => {
                    resolve(response.data)
                }, err => {
                    reject(err)
                })
        })
    },
    postblob(url, name, obj) {
        console.log(1)
        if (obj) {
            console.log(2)
            var fd = new FormData()
            fd.append('id', obj)
            let config = {
                headers: {
                    'Content-Type': 'multipart/form-data'
                }
            }
            axios({
                    method: "post",
                    url: url,
                    fd,
                    responseType: "blob",
                    config
                })
                .then(res => {
                    // console.log(decodeURI(res.headers['filename']));
                    const link = document.createElement("a");
                    let blob = new Blob([res.data], { type: "application/vnd.ms-excel" });
                    link.style.display = "none";
                    link.href = URL.createObjectURL(blob);
                    link.setAttribute("download", decodeURI(name));
                    document.body.appendChild(link);
                    link.click();
                    document.body.removeChild(link);
                })
                .catch(error => {
                    this.$Notice.error({
                        title: "错误",
                        desc: "系统数据错误"
                    });
                    console.log(error);
                });
        } else {

            axios({
                    method: "post",
                    url: url,

                    responseType: "blob",

                })
                .then(res => {
                    // console.log(decodeURI(res.headers['filename']));
                    const link = document.createElement("a");
                    let blob = new Blob([res.data], { type: "application/vnd.ms-excel" });
                    link.style.display = "none";
                    link.href = URL.createObjectURL(blob);
                    link.setAttribute("download", decodeURI(name));
                    document.body.appendChild(link);
                    link.click();
                    document.body.removeChild(link);
                })
                .catch(error => {
                    this.$Notice.error({
                        title: "错误",
                        desc: "系统数据错误"
                    });
                    console.log(error);
                });
        }
    },
    get(url, params = {}) {
        return new Promise((resolve, reject) => {
            axios.get(url, {
                    params: params
                })
                .then(response => {
                    resolve(response.data)
                })
                .catch(err => {
                    reject(err)
                })
        })
    },
    // 封装put请求和delete请求
    put(url, data = {}) {
        return new Promise((resolve, reject) => {
            axios.put(url, data)
                .then(response => {
                    resolve(response.data)
                }, err => {
                    reject(err)
                })
        })
    },
    putForm(url, data = {}) {
        return new Promise((resolve, reject) => {
            axios.put(url, qs.stringify(data), {
                    headers: {
                        'Content-Type': "application/x-www-form-urlencoded"
                    }
                })
                .then(response => {
                    resolve(response.data)
                }, err => {
                    reject(err)
                })
        })
    },
    putFile(url, data = {}) {
        return new Promise((resolve, reject) => {
            axios.put(url, data, {
                    headers: {
                        'Content-Type': 'multipart/form-data'
                    }
                })
                .then(response => {
                    resolve(response.data)
                }, err => {
                    reject(err)
                })
        })
    },
    delete(url, data = {}) {
        return new Promise((resolve, reject) => {
            axios.delete(url, data)
                .then(response => {
                    resolve(response.data)
                })
                .catch(err => {
                    reject(err)
                });
        })
    }
}
// export default axios;
